package notify

import (
	"gitee.com/bjf-fhe/apicat/entry"
	"github.com/sirupsen/logrus"
	"github.com/spf13/pflag"
)

var cacheMap = make(map[string]*entry.LogEntry)

func insert(en *entry.LogEntry) error {
	if en.Legal {
		return nil
	}
	if old, ok := cacheMap[en.Client]; ok {
		en.Count = old.Count + 1
	} else {
		en.Count = 1
	}
	cacheMap[en.Client] = en

	if currentFullNotifier != nil {
		return currentFullNotifier.Notify(cacheMap)
	} else {
		return currentIterNotifier.NotifyAdd(en)
	}

}

type Handler interface {
	AddFlags(*pflag.FlagSet)
	Init(*Config) error
}

type FullNotifier interface {
	//通过具体的推送渠道把处理过的map推送下去（所有notify中的所有map都是已经去过重的）
	Notify(map[string]*entry.LogEntry) error
}

type IterNotifier interface {
	NotifyAdd(*entry.LogEntry) error
	NotifyDel(*entry.LogEntry) error
}

var currentHandler Handler
var currentFullNotifier FullNotifier
var currentIterNotifier IterNotifier

func GetChannel(name string, currentHandler interface{}, cfg *Config) (chan *entry.LogEntry, error) {
	msgChan := make(chan *entry.LogEntry, 10)

	if fc, ok := currentHandler.(FullNotifier); ok {
		currentFullNotifier = fc
	} else {
		currentFullNotifier = nil
	}
	if fc, ok := currentHandler.(IterNotifier); ok {
		currentIterNotifier = fc
	} else {
		currentIterNotifier = nil
	}
	if currentFullNotifier == nil && currentIterNotifier == nil {
		logrus.Fatal(name + "插件错误！")
	}
	go wait(msgChan)
	return msgChan, nil
}

func wait(mc chan *entry.LogEntry) {
	for msg := range mc {
		err := insert(msg)
		if err != nil {
			logrus.Errorln("Notify error", err)
		}
	}
}
